﻿using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Dotnet.Utils.Utility.Http
{
    public static class HttpHelper
    {
        public static string DownloadString(string url, byte[] postData = null, IDictionary<string, string> headers = null, Encoding encoding = null)
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            if (postData == null)
            {
                httpWebRequest.Method = "GET";
            }
            else
            {
                httpWebRequest.Method = "POST";
                Stream requestStream = httpWebRequest.GetRequestStream();
                requestStream.Write(postData, 0, postData.Length);
                requestStream.Close();
            }
            httpWebRequest.Timeout = 100000;
            if (headers != null)
            {
                foreach (KeyValuePair<string, string> keyValuePair in headers)
                {
                    if (keyValuePair.Key.Equals("Content-Type"))
                    {
                        httpWebRequest.ContentType = keyValuePair.Value;
                    }
                    else if (keyValuePair.Key.Equals("Referer"))
                    {
                        httpWebRequest.Referer = keyValuePair.Value;
                    }
                    else
                    {
                        httpWebRequest.Headers.Add(keyValuePair.Key, keyValuePair.Value);
                    }
                }
            }
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            string result;
            using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), encoding == null ? Encoding.GetEncoding("gbk") : encoding))
            {
                result = streamReader.ReadToEnd();
            }
            httpWebResponse.Close();
            httpWebRequest.Abort();
            return result;
        }
    }
}